#!/usr/bin/env python
# -*- coding:utf-8 -*-
import configparser
import json
import os

import pandas as pd
import requests
from bottle import Bottle
from bottle import request, response

from comm.FileRoute import FileRoute
from comm.beans.SysDictObj import SysDictObj
from conn.MyLogs import MyLogs
from conn.MyRedisFactory import RedisConfig

MemwetSeduAdm = Bottle()

f = r'E:\zentao_notify\vpTransdoor\setting.ini'
config = configparser.RawConfigParser()
config.read(f, encoding='UTF8')


@MemwetSeduAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@MemwetSeduAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


class MemberWeightSeduRoute:
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    pru_tuut_db_conn = None
    rds_cfg = None
    mail_cfg = None
    _dict = None
    memeberWeightServiceImpl = None
    weightLossPlanServiceImpl = None

    arry_dinner_names = ["早餐", "午餐", "晚餐"]  # 早中晚3餐食
    arry_dinner_names_e = ["zaocan", "wucan", "wancan"]  # 早中晚3餐食
    dict_dinner_names = {"zaocan": "早餐", "wucan": "午餐", "wancan": "晚餐"}
    protein = []
    vitamin = []
    carbonWater = []
    fat = []

    def __init__(self, pru_tuut_db_conn, mailConfig, rds_cfg, memeberWeightService, weightLossPlanService):
        # MYSQL DB服务参数配置 -----------------------------------------------------------------------------------------------
        MemberWeightSeduRoute.pru_tuut_db_conn = pru_tuut_db_conn
        # RDS缓存服务参数配置 -----------------------------------------------------------------------------------------------
        MemberWeightSeduRoute.rds_cfg = rds_cfg
        # 邮件服务参数配置 -----------------------------------------------------------------------------------------------
        MemberWeightSeduRoute.mail_cfg = mailConfig
        # 业务中间层加载初始化 --------------------------------------------------------------------------------------------
        MemberWeightSeduRoute.memeberWeightServiceImpl = memeberWeightService
        MemberWeightSeduRoute.weightLossPlanServiceImpl = weightLossPlanService
        # 字典数据初始化 -------------------------------------------------------------------------------------------------
        MemberWeightSeduRoute._dict = SysDictObj(pru_tuut_db_conn)
        res = self._dict.load_dict_val(key_eng="protein")
        if res['code'] == 200:
            MemberWeightSeduRoute.protein = json.loads(res['data']['val'])
        res = self._dict.load_dict_val(key_eng="vitamin")
        if res['code'] == 200:
            MemberWeightSeduRoute.vitamin = json.loads(res['data']['val'])
        res = self._dict.load_dict_val(key_eng="carbonWater")
        if res['code'] == 200:
            MemberWeightSeduRoute.carbonWater = json.loads(res['data']['val'])
        res = self._dict.load_dict_val(key_eng="fat")
        if res['code'] == 200:
            MemberWeightSeduRoute.fat = json.loads(res['data']['val'])
        return

    @staticmethod
    @MemwetSeduAdm.get('/api/calSeduDinner')
    def chk_tot_dinner() -> None:
        import datetime
        base_url = "http://172.17.0.9:9009/hcmsed/"
        cal_day = datetime.datetime.now().strftime("%Y年%m月%d日")
        try:
            _str_val = MemberWeightSeduRoute._dict.load_dict_val(key_eng="autoDinnerLoadIndex")["data"]["val"]
            autoDinnerLoadIndex = int(_str_val)
            # 每一个新周期,刷新一次选餐内容
            if autoDinnerLoadIndex == 1:
                rps0 = requests.get(base_url + f"/makeDaysDinner?days=7&sameFoodFlg=1")
                _dit_rps0 = json.loads(rps0.text)
                if _dit_rps0["code"] != 200:
                    return
            rps1 = requests.get(base_url + f"/chkDayDinner?days=7&sameFoodFlg=1&loadIndex={autoDinnerLoadIndex}")
            _dit_rps1 = json.loads(rps1.text)
            if _dit_rps1["code"] != 200:
                return
            rps2 = requests.get(base_url + "/chkMemDinner")
            _dit_rps2 = json.loads(rps2.text)
            if _dit_rps2["code"] != 200:
                return
            rps3 = requests.get(base_url + "/chkTotDinner")
            _dit_rps3 = json.loads(rps3.text)
            if _dit_rps3["code"] != 200:
                return
            rps4 = requests.get(base_url + "/expMemDinnerExcel")
            _dit_rps4 = json.loads(rps4.text)
            if _dit_rps4["code"] != 200:
                return
            file_path = _dit_rps4['data']['path']
            file_name = _dit_rps4['data']['name']
            # 邮件唤醒 ----------------------------------------------------------------------------------------------------------
            areceiver = MemberWeightSeduRoute._dict.load_dict_val(key_eng="sendMailBox")["data"]["val"]
            acc = MemberWeightSeduRoute._dict.load_dict_val(key_eng="notifyMailBox")["data"]["val"]
            # areceiver = "suo.tianbao@vpclub.cn"
            # acc = "469605175@qq.com, 277241914@qq.com"
            mail_type = "plain"
            email_content = f"通知，{cal_day}，餐食计算数据完成"
            subject = f"{cal_day}餐食计算"
            MemberWeightSeduRoute.mail_cfg.send_file_mail(
                MemberWeightSeduRoute.mail_cfg,
                areceiver=areceiver,
                acc=acc,
                file_path=file_path,
                file_name=file_name,
                mail_msg=email_content,
                mail_title=subject)
            # 打印唤醒 ----------------------------------------------------------------------------------------------------------
            rps5 = requests.get(base_url + "/expMemDinner")
            _dit_rps5 = json.loads(rps5.text)
            # 更新数据索引坐标, 这里对一周的数据作为一个设定，如果炒作7天，则设定回第一天
            autoDinnerLoadIndex += 1
            if autoDinnerLoadIndex > 7:
                MemberWeightSeduRoute._dict.set_dict_val(key_eng="autoDinnerLoadIndex", val=1)
            else:
                MemberWeightSeduRoute._dict.set_dict_val(key_eng="autoDinnerLoadIndex", val=autoDinnerLoadIndex)

        except Exception as e1:
            MyLogs.logger.error(e1)
        return

    @staticmethod
    @MemwetSeduAdm.get('/makeDaysDinner')
    def chk_day_dinner():
        cal_days_count = int(request.params.days)  # 配餐天数
        same_food_flg = int(request.params.sameFoodFlg)  # 是否允许一天内使用重复菜品
        _str_loadIndex = request.params.loadIndex  # 指定批次的餐食数据
        try:
            # 这里隐藏一个数据BUG，如果生成天数小于，指定餐食数据时候，选取两个数值的最大值，作为生成配餐天数
            if _str_loadIndex is not None and len(_str_loadIndex) > 0:
                cal_days_count = cal_days_count if cal_days_count - int(_str_loadIndex) > 0 else int(_str_loadIndex)
            # 餐食数据初始化
            MemberWeightSeduRoute._dict.set_dict_val(key_eng="randomDinner", val="")
            # 计算主餐食中的3个随机数值
            cal_dinners_count = len(MemberWeightSeduRoute.arry_dinner_names)  # 需要生成的随机整数个数（早中晚3餐）
            group_data_list = []
            for index_day in range(cal_days_count):
                # 可选用的餐食数据初始化,初始数据来源数据字典中配置的4类食材数据
                _unused_protein_arry = MemberWeightSeduRoute.protein
                _unused_carbonWater_arry = MemberWeightSeduRoute.carbonWater
                _unused_fat_arry = MemberWeightSeduRoute.fat
                _unused_vitamin_arry = MemberWeightSeduRoute.vitamin
                # --------------------------------------------------------------------------- 食材选择算法 START
                carbonWaterCount = MemberWeightSeduRoute._dict.load_dict_val(key_eng="carbonWaterCount")["data"]["val"]
                fatCount = MemberWeightSeduRoute._dict.load_dict_val(key_eng="fatCount")["data"]["val"]
                vitaminCount = MemberWeightSeduRoute._dict.load_dict_val(key_eng="vitaminCount")["data"]["val"]
                proteinCount = MemberWeightSeduRoute._dict.load_dict_val(key_eng="proteinCount")["data"]["val"]
                [choosed_dinner_protein_array, choosed_dinner_carbonWater_array, choosed_dinner_fat_array,
                 choosed_dinner_vitamin_array] = MemberWeightSeduRoute.random_choose_dinner_data(
                    same_food_flg, cal_dinners_count, proteinCount, carbonWaterCount, fatCount, vitaminCount,
                    _unused_protein_arry, _unused_carbonWater_arry, _unused_fat_arry, _unused_vitamin_arry)
                # --------------------------------------------------------------------------- 食材选择算法
                group_data_list.append({
                    "protein": choosed_dinner_protein_array,
                    "carbonWater": choosed_dinner_carbonWater_array,
                    "fat": choosed_dinner_fat_array,
                    "vitamin": choosed_dinner_vitamin_array,
                })
                # --------------------------------------------------------------------------- 食材选择算法 END
            # 随机数据写入到字典变量中
            json_data = json.dumps(group_data_list, ensure_ascii=False)
            MemberWeightSeduRoute._dict.set_dict_val(key_eng="randomDinner", val=json_data)
            return {'code': 200, 'data': None, 'message': ""}
        except Exception as e:
            return {'code': 500, 'data': [], 'message': MemberWeightSeduRoute.ERROR_CODE["109"]}

    # 每日食材计算 菜品计算标签
    @staticmethod
    @MemwetSeduAdm.get('/chkDayDinner')
    def chk_day_dinner():
        import datetime
        _str_loadIndex = request.params.loadIndex  # 指定批次的餐食数据
        dinner_loadIndex = None
        if isinstance(_str_loadIndex, str):
            if _str_loadIndex is not None and len(_str_loadIndex) > 0:
                dinner_loadIndex = int(_str_loadIndex)
        # 字典数据初始化
        currentDate = datetime.datetime.now().strftime("%Y-%m-%d")
        group_data_list = []
        view_list = []
        try:
            # 缓存数据清空
            RedisConfig.del_val(MemberWeightSeduRoute.rds_cfg, key=f'hcm:dinner:{currentDate}')
        except Exception as e:
            print(e)
        try:
            days=[]
            _choose_cust_dinner_switch = MemberWeightSeduRoute._dict.load_dict_val(key_eng="custDinnerSw")["data"][
                "val"]
            if str(_choose_cust_dinner_switch).upper() == 'ON':
                # 使用固定餐谱
                view_list = MemberWeightSeduRoute.custom_choose_dinner_data()
                # 不指定配餐天数，按照默认条件执行全量配餐天数，
                if dinner_loadIndex is not None and dinner_loadIndex > 0:
                    # 如果选择配餐天数 < 配餐天数，选择使用配餐天数
                    if len(view_list) - dinner_loadIndex > 0:
                        view_list = [view_list[dinner_loadIndex]]
                    else:
                        # 如果选择配餐天数 > 配餐天数，会出现数据溢出，这里判定选择使用配餐天数的最后一天
                        view_list = [view_list[-1]]
                # 后置数据无法精准获得日期，指定配餐天数时候，需要使用指定的日期，这里对餐食日期做一次汇总，到打印环节介入筛选。不参与会员热量餐食计算环节
                days = [(datetime.datetime.now() + datetime.timedelta(days=idx+1)).strftime("%Y-%m-%d") for idx in range(len(view_list))]
                v = {"t": days, "d": view_list}
                # 计算数据放入到缓存中
                RedisConfig.push_val_intimes(MemberWeightSeduRoute.rds_cfg, key=f'hcm:dinner:{currentDate}',
                                             val=json.dumps(v, ensure_ascii=False),
                                             json_flg=True, inTimes=60 * 60)
                return {'code': 200, 'data': view_list, 'message': ""}
            else:
                # 计算页面参数 计算指定天数的餐食，
                str_data_list = MemberWeightSeduRoute._dict.load_dict_val(key_eng="randomDinner")["data"]["val"]
                group_days_data_list = json.loads(str_data_list)
            # 天数的餐食计算
            cal_day_idx = 0
            for choosed_oneDay_dinners_i in group_days_data_list:
                can_obj = {}
                cal_day_idx += 1
                arry_choosed_protein = choosed_oneDay_dinners_i["protein"]
                arry_choosed_vitamin = choosed_oneDay_dinners_i["vitamin"]
                arry_choosed_carbonWater = choosed_oneDay_dinners_i["carbonWater"]
                arry_choosed_fat = choosed_oneDay_dinners_i["fat"]
                # 这里拆分开一天中的早中晚，
                for _dinner_e_index in range(len(MemberWeightSeduRoute.arry_dinner_names_e)):
                    # 对计算数据重新进行排列组合，编排每一项元素捆绑到1日的3餐中
                    protein = []
                    vitamin = []
                    carbonWater = []
                    fat = []
                    # 提取数据中的四种食材元素分类, 根据3月29日调整，同类餐食计算多个
                    for same_arry_catalog_dinners in arry_choosed_protein:
                        # 计算餐食内数据
                        choosed_dinner = same_arry_catalog_dinners[_dinner_e_index]
                        # 如果计算餐食不能满足三餐内容，即选用的餐食存在不可重复要求，则会有剩余1个餐食的可能，不满足三餐的使用，则递减一次餐时数据
                        # if len(choosed_protein_s[j_idx][0]) > _dinner_e_index:
                        #     fuck = choosed_protein_s[j_idx][0][_dinner_e_index]
                        # else:
                        #     fuck = choosed_protein_s[j_idx][0][_dinner_e_index - 1]
                        protein.append(choosed_dinner)
                    for same_arry_catalog_dinners in arry_choosed_vitamin:
                        # 计算餐食内数据
                        choosed_dinner = same_arry_catalog_dinners[_dinner_e_index]
                        # if len(choosed_vitamin[j][0]) > _dinner_e_index:
                        #     fuck = choosed_vitamin[j][0][_dinner_e_index]
                        # else:
                        #     fuck = choosed_vitamin[j][0][_dinner_e_index - 1]
                        vitamin.append(choosed_dinner)
                    for same_arry_catalog_dinners in arry_choosed_carbonWater:
                        # 计算餐食内数据
                        choosed_dinner = same_arry_catalog_dinners[_dinner_e_index]
                        # if len(choosed_carbonWater[j][0]) > _dinner_e_index:
                        #     fuck = choosed_carbonWater[j][0][_dinner_e_index]
                        # else:
                        #     fuck = choosed_carbonWater[j][0][_dinner_e_index - 1]
                        carbonWater.append(choosed_dinner)
                    for same_arry_catalog_dinners in arry_choosed_fat:
                        choosed_dinner = same_arry_catalog_dinners[_dinner_e_index]
                        # if len(choosed_fat[j][0]) > _dinner_e_index:
                        #     fuck = choosed_fat[j][0][_dinner_e_index]
                        # else:
                        #     fuck = choosed_fat[j][0][_dinner_e_index - 1]
                        fat.append(choosed_dinner)
                    can_data = {"protein": protein, "vitamin": vitamin, "carbonWater": carbonWater, "fat": fat}
                    can_obj[MemberWeightSeduRoute.arry_dinner_names_e[_dinner_e_index]] = can_data
                str_cal_date = (datetime.datetime.now() + datetime.timedelta(days=cal_day_idx)).strftime(
                    "%Y-%m-%d")
                days.append(str_cal_date)
                view_list.append({"list": can_obj, "cal_day": str_cal_date})
            v = {"t": days, "d": view_list}
            # 计算数据放入到缓存中
            RedisConfig.push_val_intimes(MemberWeightSeduRoute.rds_cfg, key=f'hcm:dinner:{currentDate}',
                                         val=json.dumps(v, ensure_ascii=False),
                                         json_flg=True, inTimes=60 * 60)
            return {'code': 200, 'data': view_list, 'message': ""}
        except Exception as e:
            return {'code': 500, 'data': [], 'message': MemberWeightSeduRoute.ERROR_CODE["109"]}

    @staticmethod
    def random_choose_dinner_data(same_food_flg, cal_dinners_count, proteinCount,
                                  carbonWaterCount, fatCount, vitaminCount,
                                  _unused_protein_arry, _unused_carbonWater_arry, _unused_fat_arry,
                                  _unused_vitamin_arry):
        # 计算每一餐的数据循环, 食量默认每个品类选取1种餐食
        # 计算蛋白质, 去除已经使用的数据
        choosed_dinner_protein_array = []
        for _exec_index in range(int(proteinCount)):
            if same_food_flg == 1:
                choosed_dinner_protein = MemberWeightSeduRoute.cal_dinner_array(
                    all_dinner_array=MemberWeightSeduRoute.protein, choose_count=cal_dinners_count)
            else:
                choosed_dinner_protein = MemberWeightSeduRoute.cal_dinner_array(all_dinner_array=_unused_protein_arry,
                                                                                choose_count=cal_dinners_count)  # 获得列表中随机的3个元素
                _unused_protein_arry = cal_remove_array_index(target=choosed_dinner_protein,
                                                              datas=_unused_protein_arry,
                                                              count=len(_unused_protein_arry))  # 剔除已经用过的数据
                _unused_protein_arry = check_zero_array(_unused_protein_arry,
                                                        MemberWeightSeduRoute.protein)  # 这里判定下可用列表是否为空，需要重置列表
            choosed_dinner_protein_array.append(choosed_dinner_protein)
        # 计算碳水, 去除已经使用的数据
        choosed_dinner_carbonWater_array = []
        for _exec_index in range(int(carbonWaterCount)):
            if same_food_flg == 1:
                choosed_dinner_carbonWater = MemberWeightSeduRoute.cal_dinner_array(
                    all_dinner_array=MemberWeightSeduRoute.carbonWater, choose_count=cal_dinners_count)
            else:
                choosed_dinner_carbonWater = MemberWeightSeduRoute.cal_dinner_array(
                    all_dinner_array=_unused_carbonWater_arry, choose_count=cal_dinners_count)
                _unused_carbonWater_arry = cal_remove_array_index(target=choosed_dinner_carbonWater,
                                                                  datas=_unused_carbonWater_arry,
                                                                  count=len(_unused_carbonWater_arry))
                _unused_carbonWater_arry = check_zero_array(_unused_carbonWater_arry, MemberWeightSeduRoute.carbonWater)
            choosed_dinner_carbonWater_array.append(choosed_dinner_carbonWater)
        # 计算脂肪, 去除已经使用的数据
        choosed_dinner_fat_array = []
        for _exec_index in range(int(fatCount)):
            if same_food_flg == 1:
                choosed_dinner_fat = MemberWeightSeduRoute.cal_dinner_array(all_dinner_array=MemberWeightSeduRoute.fat,
                                                                            choose_count=cal_dinners_count)
            else:
                choosed_dinner_fat = MemberWeightSeduRoute.cal_dinner_array(all_dinner_array=_unused_fat_arry,
                                                                            choose_count=cal_dinners_count)
                _unused_fat_arry = cal_remove_array_index(target=choosed_dinner_fat,
                                                          datas=_unused_fat_arry,
                                                          count=len(_unused_fat_arry))
                _unused_fat_arry = check_zero_array(_unused_fat_arry, MemberWeightSeduRoute.fat)
            choosed_dinner_fat_array.append(choosed_dinner_fat)
        # 计算维生素
        choosed_dinner_vitamin_array = []
        for _exec_index in range(int(vitaminCount)):
            if same_food_flg == 1:
                choosed_dinner_vitamin = MemberWeightSeduRoute.cal_dinner_array(
                    all_dinner_array=MemberWeightSeduRoute.vitamin, choose_count=cal_dinners_count)
            else:
                choosed_dinner_vitamin = MemberWeightSeduRoute.cal_dinner_array(all_dinner_array=_unused_vitamin_arry,
                                                                                choose_count=cal_dinners_count)
                _unused_vitamin_arry = cal_remove_array_index(target=choosed_dinner_vitamin,
                                                              datas=_unused_vitamin_arry,
                                                              count=len(_unused_vitamin_arry))
                _unused_vitamin_arry = check_zero_array(_unused_vitamin_arry, MemberWeightSeduRoute.vitamin)
            choosed_dinner_vitamin_array.append(choosed_dinner_vitamin)
        return [choosed_dinner_protein_array, choosed_dinner_carbonWater_array, choosed_dinner_fat_array,
                choosed_dinner_vitamin_array]

    @staticmethod
    def custom_choose_dinner_data():
        import datetime
        cal_day_arry = []
        # _dict = SysDictObj(pru_tuut_db_conn)
        _choose_cust_dinner = MemberWeightSeduRoute._dict.load_dict_val(key_eng="custDinner")["data"]["val"]
        json_data_arry = json.loads(_choose_cust_dinner)
        day_arry = json_data_arry
        for day_idx in range(len(day_arry)):
            day = day_arry[day_idx]
            cal_can_Object = {}
            can_arry = day["can"]
            for can_idx in range(len(can_arry)):
                choosed_dinner_vitamin_array = []
                choosed_dinner_fat_array = []
                choosed_dinner_carbonWater_array = []
                choosed_dinner_protein_array = []
                _can = {}
                food_arry = can_arry[can_idx]["foods"]
                for food_idx in range(len(food_arry)):
                    if food_arry[food_idx]["catalog"] == "碳水化合":
                        choosed_dinner_carbonWater_array.append(food_arry[food_idx])
                    if food_arry[food_idx]["catalog"] == "脂肪":
                        choosed_dinner_fat_array.append(food_arry[food_idx])
                    if food_arry[food_idx]["catalog"] == "维生素":
                        choosed_dinner_vitamin_array.append(food_arry[food_idx])
                    if food_arry[food_idx]["catalog"] == "蛋白质":
                        choosed_dinner_protein_array.append(food_arry[food_idx])
                cal_can_Object[can_arry[can_idx]["name"]] = {"protein": choosed_dinner_protein_array,
                                                             "vitamin": choosed_dinner_vitamin_array,
                                                             "carbonWater": choosed_dinner_carbonWater_array,
                                                             "fat": choosed_dinner_fat_array}
            str_cal_date = (datetime.datetime.now() + datetime.timedelta(days=day_idx+1)).strftime("%Y-%m-%d")
            cal_day_arry.append({"list": cal_can_Object, "cal_day": str_cal_date})
        return cal_day_arry

    # 每日食材计算 热量缺口计算标签
    @staticmethod
    @MemwetSeduAdm.get('/chkMemDinner')
    def chk_member_dinner_new():
        import datetime
        currentDate = datetime.datetime.now().strftime("%Y-%m-%d")
        _obj_page_view = []
        projects_sno = str(request.params.projects)
        try:
            RedisConfig.del_val(MemberWeightSeduRoute.rds_cfg, key=f"hcm:mem:{currentDate}_mem_dinners")
            RedisConfig.del_val(MemberWeightSeduRoute.rds_cfg, key=f"hcm:mem:{currentDate}_tot_dinners")
            RedisConfig.del_val(MemberWeightSeduRoute.rds_cfg, key=f'hcm:mem:{currentDate}_tot_preday_dinners')
        except Exception as e:
            print(e)
        try:
            # 取得上一步计算的数据
            _str_arry_json = RedisConfig.get_val(MemberWeightSeduRoute.rds_cfg, key=f'hcm:dinner:{currentDate}',
                                                 json_flg=True)
            if _str_arry_json is None:
                return {'code': 109, 'data': [], 'message': MemberWeightSeduRoute.ERROR_CODE["109"]}
            _obj_json = json.loads(_str_arry_json)
            # 餐食数据
            _arry_json = _obj_json["d"]
            # 餐食对应日期数据
            days = _obj_json["t"]
            # 寻找可以计算数据的会员
            member_in_use = {"status": "MEM-001", "projects": projects_sno, "memID": None}
            _arry_member = MemberWeightSeduRoute.memeberWeightServiceImpl.fetch_member_inuse(member_in_use)
            if _arry_member['code'] == 200:
                _tot_rds_dinners = []
                _tot_single_day_dinners = {}  # 2024-03-03 需求增加每日汇总数量
                for idx in range(len(_arry_json)):
                    _tot_single_day_dinners[idx] = []
                # 清空当日的计算数据，避免类累积数据影响计算
                MemberWeightSeduRoute.clear_today_member_combination_history(cal_day=currentDate)
                for member in _arry_member['data']:
                    try:
                        member_dinner_days = []
                        _obj_view = {}
                        # 计算会员的热量缺口
                        member_heat = MemberWeightSeduRoute.memeberWeightServiceImpl.cal_member_weight(
                            view=None, memberId=member["member_id"])
                        # TODO 1 循环计算进餐天数,初始化单会员的餐食数据
                        for one_day_idx in range(len(_arry_json)):
                            one_day_data = _arry_json[one_day_idx]["list"]
                            _str_dinner_date = str(_arry_json[one_day_idx]['cal_day'])
                            MyLogs.logger.info(f" %s 日期: [{_str_dinner_date}] 热量食材计算 %s " % (("*" * 20), ("*" * 20)))
                            # TODO 2 这里调整计算方法，使用新的计算数量，一天的餐食数据 / 单日进餐数量
                            one_day_dinners = MemberWeightSeduRoute.make_one_day_dinner_in_ary(one_day_data, member_heat["data"])
                            # 根据会员摄入的食材数据，从数据库中计算餐食食材的对应摄入克重，维生素类食材不在热量计算范围内，使用1作为数据量替换，同类食材平均分配摄入重量
                            if int(member["sex"]) == 0:
                                dinner_std_weight = \
                                    MemberWeightSeduRoute._dict.load_dict_val(key_eng="mDinnerStdKgs")["data"]["val"]
                            elif int(member["sex"]) == 1:
                                dinner_std_weight = \
                                    MemberWeightSeduRoute._dict.load_dict_val(key_eng="fDinnerStdKgs")["data"]["val"]
                            _str_VitaminProportion = \
                                MemberWeightSeduRoute._dict.load_dict_val(key_eng="VitaminProportion")["data"]["val"]
                            member_dinners = MemberWeightSeduRoute.weightLossPlanServiceImpl.calculation_ingredient_ratio_with_dinner(
                                dinners=one_day_dinners,
                                dinnerStdWeight=dinner_std_weight,
                                vitaminProportion=float(_str_VitaminProportion))
                            # 配置页面数据, 会员每一天餐食-------------------------------------------------------------
                            one_member_dinners = {
                                "day": _str_dinner_date,  # 计算餐食日期
                                "dinners": member_dinners['data']['ARRY'],  # 列表形式[]
                                "dinner": member_dinners['data']['DICT']  # 字典形式{}
                            }
                            member_dinner_days.append(one_member_dinners)  # 绑定到每一天
                            # 统一单日的食材使用数据，将食材加入到汇总列表 -----------------------------------------------------
                            [_tot_rds_dinners.append(i) for i in member_dinners["data"]["TOT"]]
                            [_tot_single_day_dinners[one_day_idx].append(i) for i in member_dinners["data"]["TOT"]]
                        # 餐食与会员信息绑定，包含计算餐食天数，餐食数量, 写入持久化存储
                        _obj_view = {"memId": member["member_id"],
                                     "memSno": member["member_sno"],
                                     "memName": member["name"],
                                     "cal_day": currentDate,
                                     "days": days,
                                     "dinners": member_dinner_days}
                        # 补加计算数据加入到数据库中，会员信息，菜单信息，计算日
                        MemberWeightSeduRoute.add_member_combination_history(_obj_view)
                        _obj_page_view.append(_obj_view)  # 汇总会员数据
                    except Exception as e:
                        # 单人计算错误，跳过数据继续计算
                        MyLogs.logger.error(e)
                        continue
            MyLogs.logger.info(f" %s 全食材用量统计 %s " % (("*" * 20), ("*" * 20)))
            MyLogs.logger.info(json.dumps(_tot_rds_dinners, ensure_ascii=False))
            MyLogs.logger.info(f" %s 全食材用量统计 %s " % (("*" * 20), ("*" * 20)))
            # 结果数据放入到缓存中
            RedisConfig.push_val_intimes(MemberWeightSeduRoute.rds_cfg, key=f'hcm:mem:{currentDate}_mem_dinners',
                                         val=json.dumps(_obj_page_view, ensure_ascii=False),
                                         json_flg=True, inTimes=60 * 60)
            RedisConfig.push_val_intimes(MemberWeightSeduRoute.rds_cfg, key=f'hcm:mem:{currentDate}_tot_dinners',
                                         val=json.dumps(_tot_rds_dinners, ensure_ascii=False),
                                         json_flg=True, inTimes=60 * 60)
            RedisConfig.push_val_intimes(MemberWeightSeduRoute.rds_cfg, key=f'hcm:mem:{currentDate}_tot_preday_dinners',
                                         val=json.dumps(_tot_single_day_dinners, ensure_ascii=False),
                                         json_flg=True, inTimes=60 * 60)
            return {'code': 200, 'data': _obj_page_view, 'message': ""}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 80, 'data': [], 'message': MemberWeightSeduRoute.ERROR_CODE["80"]}

    @staticmethod
    @MemwetSeduAdm.get('/debugMemDinner')
    def debug_member_dinner_new():
        import datetime
        currentDate = datetime.datetime.now().strftime("%Y-%m-%d")
        projects_sno = str(request.params.projects)
        debug_memID = str(request.params.debug_memid)
        debug_day_idx = str(request.params.debug_day_idx)
        try:
            base_url = "http://172.17.0.9:9009/hcmsed/"
            rps0 = requests.get(base_url + f"/makeDaysDinner?days=7&sameFoodFlg=1")
            _dit_rps0 = json.loads(rps0.text)
            if _dit_rps0["code"] != 200:
                return
            rps1 = requests.get(base_url + f"/chkDayDinner?days=7&sameFoodFlg=1&loadIndex=0")
            _dit_rps1 = json.loads(rps1.text)
            if _dit_rps1["code"] != 200:
                return
        except Exception as e:
            print(e)
        try:
            _obj_view = None
            # 取得上一步计算的数据
            _str_arry_json = RedisConfig.get_val(MemberWeightSeduRoute.rds_cfg, key=f'hcm:dinner:{currentDate}', json_flg=True)
            if _str_arry_json is None:
                return {'code': 109, 'data': [], 'message': MemberWeightSeduRoute.ERROR_CODE["109"]}
            _obj_json = json.loads(_str_arry_json)
            # 餐食数据
            _arry_json = _obj_json["d"]
            # 餐食对应日期数据
            days = _obj_json["t"]
            # 寻找可以计算数据的会员
            MyLogs.logger.debug(f"验证DEBUG状态下的计算数据{ debug_memID }" + "=" * 40 + "START")
            member_in_use = {"status": "MEM-001", "projects": projects_sno, "memID": debug_memID}
            _arry_member = MemberWeightSeduRoute.memeberWeightServiceImpl.fetch_member_inuse(member_in_use)
            if _arry_member['code'] == 200:
                member = _arry_member['data'][0]
                # 计算会员的热量缺口
                member_heat = MemberWeightSeduRoute.memeberWeightServiceImpl.cal_member_weight(view=None, memberId=member["member_id"])
                # TODO 1 循环计算进餐天数,初始化单会员的餐食数据
                _day_idx = int(debug_day_idx) - 1
                for one_day_idx in range(len(_arry_json)):
                    if debug_day_idx is not None and one_day_idx == _day_idx:
                        one_day_data = _arry_json[_day_idx]["list"]
                        _str_dinner_date = str(_arry_json[_day_idx]['cal_day'])
                        MyLogs.logger.info(f" %s 日期: [{_str_dinner_date}] 热量食材计算 %s " % (("*" * 20), ("*" * 20)))
                        # TODO 2 这里调整计算方法，使用新的计算数量，一天的餐食数据 / 单日进餐数量
                        one_day_dinners = MemberWeightSeduRoute.make_one_day_dinner_in_ary(one_day_data, member_heat["data"])
                        # 根据会员摄入的食材数据，从数据库中计算餐食食材的对应摄入克重，维生素类食材不在热量计算范围内，使用1作为数据量替换，同类食材平均分配摄入重量
                        if int(member["sex"]) == 0:
                            dinner_std_weight = MemberWeightSeduRoute._dict.load_dict_val(key_eng="mDinnerStdKgs")["data"]["val"]
                        elif int(member["sex"]) == 1:
                            dinner_std_weight = MemberWeightSeduRoute._dict.load_dict_val(key_eng="fDinnerStdKgs")["data"]["val"]
                        _str_VitaminProportion = MemberWeightSeduRoute._dict.load_dict_val(key_eng="VitaminProportion")["data"]["val"]
                        member_dinners = MemberWeightSeduRoute.weightLossPlanServiceImpl.calculation_ingredient_ratio_with_dinner(
                            dinners=one_day_dinners,
                            dinnerStdWeight=dinner_std_weight,
                            vitaminProportion=float(_str_VitaminProportion))
                        # 配置页面数据, 会员每一天餐食-------------------------------------------------------------
                        str_cal_date = (datetime.datetime.now() + datetime.timedelta(days=one_day_idx)).strftime("%Y-%m-%d")
                        one_member_dinners = {
                            "day": str_cal_date,  # 计算餐食日期
                            "dinners": member_dinners['data']['ARRY'],  # 列表形式[]
                            "dinner": member_dinners['data']['DICT']  # 字典形式{}
                        }
                        # 统一单日的食材使用数据，将食材加入到汇总列表 -----------------------------------------------------
                        # 餐食与会员信息绑定，包含计算餐食天数，餐食数量, 写入持久化存储
                        _obj_view = {"memId": member["member_id"],
                                     "memSno": member["member_sno"],
                                     "memName": member["name"],
                                     "cal_day": currentDate,
                                     "days": days,
                                     "dinners": one_member_dinners}
                        return {'code': 200, 'data': _obj_view, 'message': ""}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 80, 'data': [], 'message': MemberWeightSeduRoute.ERROR_CODE["80"]}

    # 每日食材计算 食料汇总
    @staticmethod
    @MemwetSeduAdm.get('/chkTotDinner')
    def chk_tot_dinner():
        import datetime
        currentDate = datetime.datetime.now().strftime("%Y-%m-%d")
        view_one_day_list = []
        try:
            _arry_cal = []
            _str_mem_dinners_json = RedisConfig.get_val(MemberWeightSeduRoute.rds_cfg,
                                                        key=f'hcm:mem:{currentDate}_mem_dinners', json_flg=True)
            _str_tot_dinners_json = RedisConfig.get_val(MemberWeightSeduRoute.rds_cfg,
                                                        key=f'hcm:mem:{currentDate}_tot_dinners', json_flg=True)
            _str_tot_preday_dinners_json = RedisConfig.get_val(MemberWeightSeduRoute.rds_cfg,
                                                               key=f'hcm:mem:{currentDate}_tot_preday_dinners',
                                                               json_flg=True)
            if _str_mem_dinners_json is None:
                return {'code': 109, 'data': [], 'message': MemberWeightSeduRoute.ERROR_CODE["109"]}
            # 计算会员数据 ---------------------------------------------------------------------------------------
            _arry_members = json.loads(_str_mem_dinners_json)
            # 计算单日食材 ---------------------------------------------------------------------------------------
            _dict_tot_preday_dinners = json.loads(_str_tot_preday_dinners_json)
            for key, value in _dict_tot_preday_dinners.items():
                one_day_tot_foods = make_tot_dinner_in_days(value)
                view_one_day_list.append({"day": int(key) + 1, "foods": one_day_tot_foods})
            # 汇总计算食材 ---------------------------------------------------------------------------------------
            _dict_tot_dinners = json.loads(_str_tot_dinners_json)
            # 数据汇总去重
            # view_tot_food_list = add_arry_same_elements(_dict_tot_dinners, _dict_tot_dinners)
            view_tot_food_list = add_same_elements_in_one_arry(_dict_tot_dinners)
            return {'code': 200,
                    'data': {"list": view_one_day_list, "tot": view_tot_food_list, "cal_day": currentDate},
                    'message': ""}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 80, 'data': [], 'message': MemberWeightSeduRoute.ERROR_CODE["80"]}

    # Excel 数据导出
    @staticmethod
    @MemwetSeduAdm.get('/expMemDinnerExcel')
    def exp_mem_dinner_excel():
        from os.path import exists as file_exists
        import datetime
        currentDate = datetime.datetime.now().strftime("%Y-%m-%d")
        res = MemberWeightSeduRoute.fetch_combination_tot(cal_date=currentDate)
        if res["code"] == 200:
            if len(res["data"]) == 0:
                return {'code': 401, 'data': [], 'message': "餐食计算数据异常，请重新计算。"}
            ikk_days = res["ikk"]
            csv_title = ["日期", "会员编号", "餐食", "食材", "克重"]
            # 按照，会员，餐时，餐品，克重 导出excel
            csv_data = [[item["day"], item["m"], item["dinner"], item["food"], item["kgs"]] for item in res["data"]]
            save_path = FileRoute.get_save_path_for_category("excel")
            if not file_exists(save_path):
                os.makedirs(save_path)
            save_file_name = f"{str(currentDate).replace('-', '')}dinners.csv"
            save_file_path = f"{save_path}" + save_file_name
            if file_exists(save_file_path):
                os.remove(save_file_path)
            try:
                write_csv = save_file_path
                df = pd.DataFrame(data=csv_data, columns=csv_title)
                df.to_csv(write_csv, index=False, header=True)
            except Exception as e:
                MyLogs.logger.error("ERROR: %s" % e)
            _data = {"name": save_file_name,
                     "path": save_file_path,
                     "url": config['upload']['file_server'] + save_file_name}
            return {'code': 200, 'data': _data, 'message': ""}
        return {'code': 500, 'data': None, 'message': MemberWeightSeduRoute.ERROR_CODE["109"]}

    @staticmethod
    @MemwetSeduAdm.get('/expClrCache')
    def exp_clr_cache():
        import datetime
        try:
            # 清空当前计算日的所有缓存信息
            cal_day = datetime.datetime.now().strftime("%Y-%m-%d")
            RedisConfig.del_val(MemberWeightSeduRoute.rds_cfg, key=f'hcm:dinner:{cal_day}')
            RedisConfig.del_val(MemberWeightSeduRoute.rds_cfg, key=f"hcm:mem:{cal_day}_mem_dinners")
            RedisConfig.del_val(MemberWeightSeduRoute.rds_cfg, key=f"hcm:mem:{cal_day}_tot_dinners")
            # 清空餐谱
            MemberWeightSeduRoute._dict.set_dict_val(key_eng="randomDinner", val="")
            return {'code': 200, 'data': None, 'message': ""}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 500, 'data': None, 'message': MemberWeightSeduRoute.ERROR_CODE["109"]}

    # 会员热量缺口餐食历史记录 ------------------------------------------------------------------------------- START
    @staticmethod
    def add_member_combination_history(combinations):
        try:
            ary_vals = "'" + json.dumps(combinations['dinners'], ensure_ascii=False) + "'" \
                       + ", '" + combinations['memId'] + "'" \
                       + ", '" + combinations['cal_day'] + "'" \
                       + ", '" + json.dumps(combinations['days'], ensure_ascii=False) + "'"
            insert_sql = f" INSERT INTO `mem_member_combination` (`dinners`,`memId`,`cal_day`,`ikk_day`) " \
                         " VALUES ( %s )" % ary_vals
            MemberWeightSeduRoute.pru_tuut_db_conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    # 清除当天数据库中会员的餐食计算记录
    @staticmethod
    def clear_today_member_combination_history(cal_day):
        try:
            delete_sql = f" DELETE FROM `mem_member_combination` WHERE `cal_day` = \'{cal_day}\' "
            MemberWeightSeduRoute.pru_tuut_db_conn.sql_commit(delete_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    # 数据库中读取会员的餐食计算记录
    @staticmethod
    def fetch_combination_tot(cal_date: str):
        res_arry = []
        try:
            fetch_sql = f" SELECT `id`,`dinners`,`memId`,`cal_day`,`ikk_day` " \
                        f" FROM `mem_member_combination`" \
                        f" WHERE 1=1 AND `cal_day` = \'{cal_date}\'" \
                        f" ORDER BY `cal_day` DESC "
            fetch_mem_sql = f" SELECT `NAME`, `MEMBER_SNO` " \
                            f" FROM `view_member`" \
                            f" WHERE 1=1 AND `MEMBER_ID` = \'%s\'"
            items = MemberWeightSeduRoute.pru_tuut_db_conn.sql_execute(fetch_sql)
            if len(items) > 0:
                res = [chgData(item) for item in items]
                for one_mem in res:
                    mem_data = MemberWeightSeduRoute.pru_tuut_db_conn.sql_execute(fetch_mem_sql % one_mem["memId"])
                    str_combination_dinners = one_mem['dinners']
                    day_dinners = json.loads(str_combination_dinners)
                    for one_day in day_dinners:
                        dinners = one_day["dinners"]
                        z1 = dinners[0]
                        for za in z1["zaocan"]:
                            _obj = {"day": one_day["day"],
                                    "m": mem_data[0][0],
                                    "mid": mem_data[0][1],
                                    "dinner": "早餐",
                                    "food": za["name"],
                                    "kgs": za["intake"]}
                            res_arry.append(_obj)
                        z2 = dinners[1]
                        for zb in z2["wucan"]:
                            _obj = {"day": one_day["day"],
                                    "m": mem_data[0][0],
                                    "mid": mem_data[0][1],
                                    "dinner": "午餐",
                                    "food": zb["name"],
                                    "kgs": zb["intake"]}
                            res_arry.append(_obj)
                        z3 = dinners[2]
                        for zc in z3["wancan"]:
                            _obj = {"day": one_day["day"],
                                    "m": mem_data[0][0],
                                    "mid": mem_data[0][1],
                                    "dinner": "晚餐",
                                    "food": zc["name"],
                                    "kgs": zc["intake"]}
                            res_arry.append(_obj)
                    # 历史数据进行排序
                    # sorted_dict_list = sorted(one_mem_tot, key=lambda x: x['name'])
                    # print(json.dumps(res_arry, ensure_ascii=False))
            return {"code": 200, "data": res_arry, "ikk": res[0]["ikk_day"]}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    # 会员热量缺口餐食历史记录 ------------------------------------------------------------------------------- END
    # TODO 2024-03-16 3-1 加入一键清空缓存
    @staticmethod
    def cal_dinner_array(all_dinner_array, choose_count):
        end = len(all_dinner_array)
        # 计算下标队列，计算剩余可用数据，如果剩余1条，则默认选择剩余值
        if end == 1:
            choosed_dinner_index = [0 for i in range(end)]
        else:
            # 生成随机数据
            choosed_dinner_index = cal_random_single_data_in_count(choose_count, len(all_dinner_array))
        return [all_dinner_array[i] for i in choosed_dinner_index]

    # 餐食数据，会员数据通过本方法进行调整与计算。
    # Warning 这里修改后，需要调整页面中的数据组合。
    # DATE: 2024/04/02
    # UPDATE: 加入固定餐食计算内容
    # RETURN: 根据用户的体征热量信息，平均计算每日三餐中每一餐，每一类元素，每一份食材的需要摄入克重值
    @staticmethod
    def make_one_day_dinner_in_ary(one_day_data, member_heat_gap):
        _ary_dinner_time = ["zaocan", "wucan", "wancan"]
        _ary_dinner_time_chn_name = ["早餐", "午餐", "晚餐"]
        _ary_cat_eng_name = ["protein", "carbonWater", "fat", "vitamin"]
        _ary_cat_chn_name = ["蛋白质", "碳水", "脂肪", "维生素"]
        _ary_mem_catalog_weight_name = ["proteinWeight", "carbonWaterWeight", "fatWeight", "vitaminWeight"]
        one_day_dinners = []
        MyLogs.logger.info(f" %s 会员: [{member_heat_gap['name']}]热量食材计算 %s " % (("*" * 20), ("*" * 20)))
        # 一日内餐品的数量循环
        for _ary_key_idx in range(len(_ary_dinner_time)):
            MyLogs.logger.info(
                f"计算餐时[{', '.join(_ary_dinner_time_chn_name)}]: %s [{_ary_dinner_time_chn_name[_ary_key_idx]}]" % (
                        "=" * 20))
            target_obj = {}
            food_obj = {}
            # 这里是食材类别循环
            for _ary_cat_idx in range(len(_ary_cat_eng_name)):
                _can_catalog_list = one_day_data[_ary_dinner_time[_ary_key_idx]][_ary_cat_eng_name[_ary_cat_idx]]
                if len(_can_catalog_list) > 1:
                    MyLogs.logger.info("出现同类餐品食材, %s: %s" % (
                        _ary_cat_chn_name[_ary_cat_idx], ",".join([i["name"] for i in _can_catalog_list])))
                MyLogs.logger.info(f"计算单类食材摄入总克重: %s [{_ary_cat_chn_name[_ary_cat_idx]}] %s(克)" %
                                   (("-" * 20), str(member_heat_gap[_ary_mem_catalog_weight_name[_ary_cat_idx]])))
                # 这里是同类别食材的数量循环
                food_obj[_ary_mem_catalog_weight_name[_ary_cat_idx]] = [{
                    "name": i["name"],
                    "intake": 0,
                    "key": _ary_cat_chn_name[_ary_cat_idx],
                    "food": {
                        "catalog": i['catalog'],
                        "name": i['key'],
                        "single_food_weight": member_heat_gap[_ary_mem_catalog_weight_name[_ary_cat_idx]] / len(
                            _ary_dinner_time) / len(_can_catalog_list),  # 这里对三餐食材数量平均到每一餐，每一类食材数量的单一重量
                    }
                } for i in _can_catalog_list]
                for i in _can_catalog_list:
                    MyLogs.logger.info(f"计算食材摄入克重: %s [{i['name']}] %s " % (("-" * 20), str(
                        round(member_heat_gap[_ary_mem_catalog_weight_name[_ary_cat_idx]] / len(_ary_dinner_time) / len(
                            _can_catalog_list), 2)
                    )))
                target_obj[_ary_dinner_time[_ary_key_idx]] = food_obj
                target_obj["dinner"] = _ary_dinner_time[_ary_key_idx]
            one_day_dinners.append(target_obj)
        MyLogs.logger.info(f" %s 热量食材计算 %s " % (("*" * 20), ("*" * 20)))
        return one_day_dinners

    @staticmethod
    @MemwetSeduAdm.get('/fetchProjectsOpts')
    def fetch_projects_options():
        try:
            fetch_opts_sql = f" SELECT `name`,`camp_sno` FROM `mem_projects` "
            opt_datas = MemberWeightSeduRoute.pru_tuut_db_conn.sql_execute(fetch_opts_sql)
            if len(opt_datas) > 0:
                res = [{"key": data[1], "label": data[0], "value": data[1]} for data in opt_datas]
                return {"code": 200, "data": res}
            return {"code": 200, "data": []}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}


# 汇总会员餐食数据组集合，并去除重复项目
def make_tot_dinner_in_days(one_day):
    _arrrys = []
    # 会员得到的计算天数是统一的,数据汇总去重
    # _ary_day_tot_food = add_arry_same_elements(one_day, one_day)
    _ary_day_tot_food = add_same_elements_in_one_arry(one_day)
    return _ary_day_tot_food


# 判定列表数据，空列表则返回总序列，否则返回当前列表
def check_zero_array(target, data):
    if len(target) == 0:
        return data
    return target


# 按照 count 数量随机获取序列内的数据下标
def cal_random_single_data_in_count(count, range_size):
    import random
    res = []
    _arry_in = [i for i in range(range_size)]
    for _index_count in range(count):
        if len(_arry_in) > 0:
            used = random.choice(_arry_in)
            _arry_in.remove(used)
            res.append(used)
    return res


# 数据库DB转换页面对象
def chgData(obj):
    return {"id": obj[0], "dinners": obj[1], "memId": obj[2], "cal_day": obj[3], "ikk_day": obj[4]}


# 总队列中删除重复的元素
# target = 已使用元素
# datas = 待使用元素
# count = 比较列表可用元素总数
def cal_remove_array_index(target, datas, count):
    _tot = [i for i in datas]
    if count <= 0:
        return
    for compare_val in target:
        for _data_val in _tot:
            if _data_val['name'] == compare_val['name']:
                _tot.remove(_data_val)
    return _tot


def add_arry_same_elements(arryA, arryB):
    from itertools import groupby
    dinner_groups = [list(arryA) for key, group in groupby(arryA, key=lambda x: x['name'])]
    same_key = [item['name'] for item in arryB]
    count_dict = {arryB[i]["name"]: 0 for i in range(len(arryB))}
    try:
        for cal_item in arryA:
            if cal_item['name'] in same_key:
                count_dict[cal_item['name']] += cal_item['intake']
            else:
                count_dict[cal_item['name']] = cal_item['intake']
                same_key.append(cal_item['name'])
        return [{"name": key, "intake": value} for key, value in count_dict.items()]
    except Exception as e:
        print(e)


def add_same_elements_in_one_arry(arryA):
    count_dict = {arryA[i]["name"]: 0 for i in range(len(arryA))}  # 数组序列去重
    same_key = []
    try:
        for cal_item in arryA:
            if cal_item['name'] in same_key:
                count_dict[cal_item['name']] += cal_item['intake']
            else:
                count_dict[cal_item['name']] = cal_item['intake']
                same_key.append(cal_item['name'])
        return [{"name": key, "intake": value} for key, value in count_dict.items()]
    except Exception as e:
        print(e)
